import BaseObj from "../BaseObj";
import { Vector2 } from "../math/Vector2";
import MathUtil from "../utils/MathUtil";

export default class BaseHome extends BaseObj {

    lines: Line[] = []
    gap: number = 5
    nowFrame = 1
    lineWidth:number = 1
    constructor(x: number, y: number) {
        super();
        this.x = x;
        this.y = y;
        this.resetLines()
    }
    resetLines() {
        let lineNum = ~~(Math.random() * 20 + 10)
        let nowLineNum = this.lines.length
        if (nowLineNum > lineNum) {
            this.lines.splice(lineNum);
        } else {
            for (let i = 0; i < (lineNum - nowLineNum); i++) {
                this.lines.push(new Line())
            }
        }
        this.lineWidth = Math.random() > 0.5 ? 1 : 2
        let angle = 360 / lineNum
        for (let i = 0; i < lineNum; i++) {
            let  randomStart= ~~(Math.random()*10)
            let nowRad = MathUtil.toRad(i * angle+randomStart)
            let nowLine = this.lines[i]
            nowLine.startPos.x = this.x
            nowLine.startPos.y = this.y
            let nowLineLength = ~~(Math.random() * 30 + 40)
            nowLine.endPos.x = this.x + nowLineLength * Math.cos(nowRad)
            nowLine.endPos.y = this.y + nowLineLength * Math.sin(nowRad)

        }
    }

    draw(ctx: CanvasRenderingContext2D) {
        ctx.fillStyle = "black"
        ctx.strokeStyle =  "black"

     
        //画线
        if (this.lines.length > 0) {
            ctx.save()
            ctx.lineWidth = this.lineWidth
            ctx.beginPath()
            this.lines.forEach(line => {
                ctx.moveTo(line.startPos.x, line.startPos.y);
                ctx.lineTo(line.endPos.x, line.endPos.y)    
            })
            
            ctx.stroke()
            ctx.closePath()
            ctx.restore()
        }
        //填充圆
        ctx.beginPath()
        ctx.arc(this.x, this.y, 40, 0, 360)
        ctx.fill()
        ctx.closePath()


        ctx.strokeStyle =  "white"
        ctx.beginPath()
        ctx.arc(this.x, this.y, 32, 0, Math.PI*2)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.arc(this.x, this.y, 36, 0, Math.PI*2)
        
        ctx.stroke()
        ctx.closePath()
    }
    update(): void {
        this.nowFrame = this.nowFrame % this.gap
        if (this.nowFrame == 0) { 
            this.resetLines()
        }
        this.nowFrame++
    }
}

class Line {
    startPos: Vector2
    endPos: Vector2
    constructor()
    constructor(startPos?: Vector2, endPos?: Vector2) {
        this.startPos = startPos ? startPos : new Vector2()
        this.endPos = endPos ? endPos : new Vector2()
    }
}